package com.atzxh.guigu.juc.lock;

public class SaleTicket {
    public static void main(String[] args) {
        // 三个售票员，卖出30张票
        Ticket ticket = new Ticket();
        // 创建三个线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用方法
                for (int i = 0; i < 30; i++) {
                    ticket.sale();
                }
            }
        },"aa").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用方法
                for (int i = 0; i < 30; i++) {
                    ticket.sale();
                }
            }
        },"bb").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 调用方法
                for (int i = 0; i < 30; i++) {
                    ticket.sale();
                }
            }
        },"cc").start();
    }
}


class Ticket {
    private int num = 30;

    public synchronized void sale() {
        // 判断是否有票
        if (num > 0) {
            num--;
            System.out.println(Thread.currentThread().getName() + ": 卖出 :" + (30 - num) + "，剩余：" + num + "张票");
        } else {
            System.out.println("票已售空");
        }
    }
}
